import React from 'react'
import { Toast } from 'antd-mobile'
import classNames from 'classnames'

import NavHeader from '../../components/NavHeader'
import { getCurrentCity } from '../../utils/getCurrentCity'
import axios from '../../utils/request'

import styles from './index.module.scss'

const baseURL = 'http://localhost:8080'

const labelStyle = {
  cursor: 'pointer',
  border: '0px solid rgb(255, 0, 0)',
  padding: '0px',
  whiteSpace: 'nowrap',
  fontSize: '12px',
  color: 'rgb(255, 255, 255)',
  textAlign: 'center'
}

// 百度地图API
const BMap = window.BMap
export default class Map extends React.Component {
  state = {
    isShowList: false,
    houseList: []
  }
  async componentDidMount() {
    //实例化地图
    this.map = new BMap.Map('container')

    const { label, value: cityId } = await getCurrentCity()
    // 创建地址解析器实例
    const myGeo = new BMap.Geocoder()
    // 将地址解析结果显示在地图上，并调整地图视野
    myGeo.getPoint(
      null,
      point => {
        if (point) {
          this.map.centerAndZoom(point, 11)
        }
      },
      label
    )
    this.renderOverlays(cityId)

    //地图api  移动地图则隐藏房源列表
    this.map.addEventListener('movestart', () => {
      if (!this.state.isShowList) return
      this.setState({ isShowList: false })
    })

    this.map.addControl(new BMap.NavigationControl())
    this.map.addControl(new BMap.ScaleControl())
  }

  async renderOverlays(cityId) {
    try {
      Toast.loading('加载中...', 0, null, false)
      const { body } = await axios.get(`/area/map?id=${cityId}`)
      Toast.hide()
      // console.log(body)
      const { nextZoom, targetType } = this.getTypeAndZoom()
      if (targetType === 'circle') {
        this.createCircle(body, nextZoom)
      } else {
        this.createRect(body)
      }
    } catch (err) {
      Toast.hide()
    }
  }

  getTypeAndZoom() {
    const zoom = this.map.getZoom()
    // console.log(zoom)
    let nextZoom, targetType
    if (zoom <= 11) {
      nextZoom = 13
      targetType = 'circle'
    } else if (zoom > 11 && zoom <= 13) {
      nextZoom = 15
      targetType = 'circle'
    } else if (zoom > 13) {
      targetType = 'rect'
    }
    return { nextZoom, targetType }
  }

  createCircle(body, nextZoom) {
    // console.log('circle')
    body.forEach(e => {
      const {
        label,
        count,
        value: areaId,
        coord: { latitude, longitude }
      } = e
      // console.log(label)
      const point = new BMap.Point(longitude, latitude)
      const opts = {
        position: point, // 指定文本标注所在的地理位置
        offset: new BMap.Size(-35, -35) //设置文本偏移量
      }
      const label1 = new BMap.Label('', opts) // 创建文本标注对象
      label1.setStyle(labelStyle)
      this.map.addOverlay(label1)
      label1.setContent(`
        <div class="${styles.bubble}">
          <p class="${styles.name}">${label}</p>
          <p>${count}</p>
        </div>
      `)
      label1.addEventListener('click', () => {
        // this.getTypeAndZoom()
        setTimeout(() => {
          // 清除当前覆盖物信息
          this.map.clearOverlays()
        }, 0)

        this.map.centerAndZoom(point, nextZoom)
        this.renderOverlays(areaId)
      })
    })
  }
  createRect(body) {
    body.forEach(e => {
      const {
        label,
        count,
        value: areaId,
        coord: { latitude, longitude }
      } = e
      // console.log(label)
      const point = new BMap.Point(longitude, latitude)
      const opts = {
        position: point, // 指定文本标注所在的地理位置
        offset: new BMap.Size(-35, -35) //设置文本偏移量
      }
      const label1 = new BMap.Label('', opts) // 创建文本标注对象
      label1.setStyle(labelStyle)
      this.map.addOverlay(label1)
      label1.setContent(`
      <div class="${styles.rect}">
        <span class="${styles.housename}">${label}</span>
        <span class="${styles.housenum}">${count}套</span>
        <i class="${styles.arrow}"></i>
      </div>
    `)
      label1.addEventListener('click', e => {
        // console.log(e)
        //点击目标的坐标
        const { clientX, clientY } = e.changedTouches[0]
        // console.log(clientX, clientY)
        //计算视图区中心点坐标
        const centerX = window.innerWidth / 2
        const centerY = (window.innerHeight - 330) / 2

        //位移计算
        const x = centerX - clientX
        const y = centerY - clientY

        //地图位移api
        this.map.panBy(x, y)

        this.getHouse(areaId).then(({ list }) => {
          this.setState({ isShowList: true, houseList: list })
        })
      })
    })
  }

  async getHouse(areaId) {
    Toast.loading('加载中...', 0, null, false)
    const { body } = await axios.get(`/houses?cityId=${areaId}`)
    // console.log(body)
    Toast.hide()
    return body
  }

  renderHouseTab = () => {
    // console.log(this.state.houseList)
    return (
      <div
        className={classNames(styles.houseList, {
          [styles.show]: this.state.isShowList
        })}
      >
        <div className={styles.titleWrap}>
          <h1 className={styles.listTitle}>房屋列表</h1>
          <a className={styles.titleMore} href="/house/list">
            更多房源
          </a>
        </div>

        {this.state.houseList.map((e, index) => {
          return (
            <div className={styles.houseItems} key={index}>
              <div className={styles.house}>
                <div className={styles.imgWrap}>
                  <img
                    className={styles.img}
                    src={`${baseURL}${e.houseImg}`}
                    alt=""
                  />
                </div>
                <div className={styles.content}>
                  <h3 className={styles.title}>{e.title}</h3>
                  <div className={styles.desc}>{e.desc}</div>
                  <div>
                    {e.tags.map((e, index) => {
                      const tagClass = `tag${index + 1}`
                      return (
                        <span
                          className={classNames(styles.tag, styles[tagClass])}
                          key={index}
                        >
                          近地铁
                        </span>
                      )
                    })}
                  </div>
                  <div className={styles.price}>
                    <span className={styles.priceNum}>{e.price}</span> 元/月
                  </div>
                </div>
              </div>
            </div>
          )
        })}
      </div>
    )
  }

  render() {
    return (
      <div className={styles.mapBox}>
        <NavHeader>地图找房</NavHeader>
        <div id="container" className={styles.container}></div>
        {this.renderHouseTab()}
      </div>
    )
  }
}
